package org.jsping.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.jsping.dao.IUserDao;
import org.jsping.entity.User;

public class UserDaoImpl extends BaseDao implements IUserDao {
	
	/**
	 * 根据openid查找一个用户
	 * @throws SQLException 
	 */
	@Override
	public User getAUser(String opid) throws SQLException {
		User user = null;
		String sql = "SELECT * FROM `User` WHERE Openid = ?";
		ResultSet rs = this.executeQuery(sql, opid);
		try {
			if(rs.next()) {
				user = new User();
				user.setUid(rs.getInt("Uid"));
				user.setUname(rs.getString("Uname"));
				user.setPwd(rs.getString("Pwd"));
				user.setOpenid(rs.getString("Openid"));
				user.setSex(rs.getInt("Sex"));
				user.setPhone(rs.getString("Phone"));
				user.setBirth(rs.getString("Birth"));
				user.setAddress(rs.getString("Address"));
				user.setImage(rs.getString("Image"));
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			this.releaseAll();
		}
		return user;
	}
	
	/**
	 * 根据用户名密码查找一个用户
	 * @throws SQLException 
	 */
	@Override
	public User getAUser(String uname, String pwd) throws SQLException {
		User user = null;
		String sql = "SELECT * FROM `User` WHERE Uname = ? and Pwd = ?";
		ResultSet rs = this.executeQuery(sql,uname,pwd);
		try {
			if(rs.next()) {
				user = new User();
				user.setUid(rs.getInt("Uid"));
				user.setUname(rs.getString("Uname"));
				user.setPwd(rs.getString("Pwd"));
				user.setOpenid(rs.getString("Openid"));
				user.setSex(rs.getInt("Sex"));
				user.setPhone(rs.getString("Phone"));
				user.setBirth(rs.getString("Birth"));
				user.setAddress(rs.getString("Address"));
				user.setImage(rs.getString("Image"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			this.releaseAll();
		}
		return user;
	}
	
	/**
	 * 添加一个qq用户或者微信用户
	 * @throws SQLException 
	 */
	@Override
	public boolean addOpenUser(User user) throws SQLException {
		String sql = "INSERT User(Uname,Sex,Openid,Image) VALUES(?,?,?,?)";
		int num = this.executeUpdate(sql, user.getUname(),user.getSex(),user.getOpenid(),user.getImage());
		if(num>0) {
			return true;
		}
		return false;
	}
	
	@Override
	public User obtain(String openid) {
		String sql = "select * from `User` where Openid = ?";
		User u = null;
		try {
			ResultSet rs = this.executeQuery(sql, openid);
			while (rs.next()) {
				u = new User();
				u.setUid(rs.getInt("Uid"));
				u.setAddress(rs.getString("Address"));
				u.setBirth(rs.getString("Birth"));
				u.setImage(rs.getString("Image"));
				u.setOpenid(rs.getString("Openid"));
				u.setPhone(rs.getString("Phone"));
				u.setPwd(rs.getString("Pwd"));
				u.setSex(rs.getInt("Sex"));
				u.setUname(rs.getString("Uname"));
			}
			return u;
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			this.releaseAll();
		}
		return u;
	}
}
